package com.djin.wx.sign.controller;

import com.soecode.wxtools.api.IService;
import com.soecode.wxtools.api.WxConfig;
import com.soecode.wxtools.api.WxService;
import com.soecode.wxtools.exception.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.util.UrlPathHelper;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author jdd
 */
@Controller
public class FileController {

    @RequestMapping("/")
    public String toPage() {
        return "upload";
    }

    private WxConfig wxConfig = new WxConfig();

    private IService iService = new WxService();

    private static final Logger logger = LoggerFactory.getLogger(WechatController.class);

    private String getDomain(HttpServletRequest request){
        StringBuffer url = request.getRequestURL();
        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).append("/").toString();
        return tempContextUrl;
    }

    @RequestMapping("/vedio")
    public String toVedio(Model model, String message, HttpServletRequest request) {

        model.addAttribute("messageUrl", "http://homily.cn/static/" + message);
        model.addAttribute("message", "/" + message);
        model.addAttribute("messageId", message);
        String appId = wxConfig.getAppId();
        long timestamp = System.currentTimeMillis() / 1000;
        String nonceStr = UUID.randomUUID().toString();
        Map<String, String> shakeMap = new HashMap<>();
        shakeMap.put("appId", appId);
        String url = getLocation(request);
        logger.debug("url:{}",url);
        System.out.println("========="+url);
        shakeMap.put("timestamp", String.valueOf(timestamp));
        shakeMap.put("nonceStr", nonceStr);
        String jsapi_ticket = "";
        try {
            jsapi_ticket =iService.getJsapiTicket();
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        String str = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonceStr +
                "&timestamp=" + timestamp +
                "&url=" + url;
        String signature = SHA1(str);
        shakeMap.put("signature", signature);
        shakeMap.put("url",url);
        model.addAttribute("shakeMap", shakeMap);
        return "example";
    }

    private String getSign(Map<String, String> params, String ticket) {
        String signature = "";
        String sign = "jsapi_ticket=" + ticket + "&noncestr=" + params.get("nonceStr") + "&timestamp=" + params.get("timestamp") + "&url=" + params.get("url");
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(sign.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return signature;
    }

    /**
     * 方法名：byteToHex</br>
     * 详述：字符串加密辅助方法 </br>
     * 开发人员：souvc  </br>
     * 创建时间：2016-1-5  </br>
     *
     * @param hash
     * @return 说明返回值含义
     * @throws
     */
    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;

    }

    /**
     * @author：罗国辉
     * @date： 2015年12月17日 上午9:24:43
     * @description： SHA、SHA1加密
     * @parameter： str：待加密字符串
     * @return： 加密串
     **/
    public static String SHA1(String str) {
        try {
            //如果是SHA加密只需要将"SHA-1"改成"SHA"即可
            MessageDigest digest = java.security.MessageDigest
                    .getInstance("SHA-1");
            digest.update(str.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexStr = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexStr.append(0);
                }
                hexStr.append(shaHex);
            }
            return hexStr.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getLocation(HttpServletRequest request)
    {
        UrlPathHelper helper = new UrlPathHelper();
        StringBuffer buff = request.getRequestURL();
        String uri = request.getRequestURI();
        String origUri = helper.getOriginatingRequestUri(request);
        buff.replace(buff.length() - uri.length(), buff.length(), origUri);
        String queryString = helper.getOriginatingQueryString(request);
        if (queryString != null)
        {
            buff.append("?").append(queryString);
        }
        return buff.toString();
    }
}
